/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUI.java
 *
 * Created on 19-oct-2011, 18:09:34
 */
package edu.sjb_beta1.gui;

import edu.sjb_beta1.characters.Mario;
import edu.sjb_beta1.map.Map;
import edu.sjb_beta1.thread.ColisionThread;
import edu.sjb_beta1.thread.GravityThread;
import edu.sjb_beta1.thread.MarioLeftUpdaterThread;
import edu.sjb_beta1.thread.MarioRightUpdaterThread;
import edu.sjb_beta1.thread.MarioUpUpdaterThread;

import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import org.ini4j.Ini;
import org.ini4j.InvalidFileFormatException;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/**
 *
 * @author Francisco
 */
public class GUI extends javax.swing.JFrame implements KeyListener {

    /** Creates new form GUI */
    public GUI(File l) {
        try {
            levelINI = new Ini(l);
        } catch (InvalidFileFormatException ex) {
            JOptionPane.showMessageDialog(this, String.format("Error on parsing %s!", l.getName()), "ERROR #2", JOptionPane.ERROR_MESSAGE);
            System.exit(2);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, String.format("Could not open %s!", l.getName()), "ERROR #2", JOptionPane.ERROR_MESSAGE);
            System.exit(4);
        }
        initComponents();
        colision= new ColisionThread();
        colision.start();
       
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        layeredPane = new javax.swing.JLayeredPane();
        {
        	mario = new Mario();
        	marioRepainter = new Thread(mario);
        	marioRepainter.start();
        	layeredPane.add(mario, JLayeredPane.POPUP_LAYER);
        	mario.setPreferredSize(new java.awt.Dimension(32, 64));
        	mario.setSize(32, 64);
        	mario.setMaximumSize(new java.awt.Dimension(32, 64));
        	mario.setMinimumSize(new java.awt.Dimension(32, 64));
        	mario.setOpaque(false);
        }

    	drawPanel = new javax.swing.JPanel();
        levelMap = new Map(1,1);
        try {
            levelMap.loadMapFromIni(levelINI);
        }
        catch (InvalidFileFormatException e) {
            JOptionPane.showMessageDialog(this, "Error on parsing \"levels/test1.sjl\"!", "ERROR #2", JOptionPane.ERROR_MESSAGE);
            System.exit(4);
        }
        int mapWidth = levelMap.getWidth();
        int mapHeigth = levelMap.getHeigth();
        drawPanel.setLayout(new GridLayout(mapWidth, mapHeigth));
        for (int h = mapHeigth-1; h >= 0; h--)  {
            for (int w = 0; w < mapWidth; w++) {
                JLabel currentJL = new JLabel();
                currentJL.setIcon(levelMap.getElementAt(w, h).getImage());
                currentJL.setSize(32,32);
                currentJL.setLocation(w*32, h*32);
                drawPanel.add(currentJL);
            }
        }
        
        backgroundPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Super JAVA Bros [Beta 1]");
        setResizable(false);

        drawPanel.setBackground(new java.awt.Color(227, 227, 227));
        drawPanel.setOpaque(false);

        drawPanel.setLayout(null);

        drawPanel.setBounds(0, 0, 800, 600);
        layeredPane.add(drawPanel, JLayeredPane.MODAL_LAYER);

        backgroundPanel.setBackground(new java.awt.Color(102, 255, 255));
        backgroundPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        backgroundPanel.setLayout(null);

        backgroundPanel.setBounds(0, 0, 800, 600);
        layeredPane.add(backgroundPanel, javax.swing.JLayeredPane.PALETTE_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        this.addKeyListener(this);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(layeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(layeredPane, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
        );
  //      gravityThread = new GravityThread();
        pack();
        this.setSize(800, 640);
    }// </editor-fold>//GEN-END:initComponents
    
    @Override
	public void keyPressed(KeyEvent e) {
    	switch (e.getKeyCode()) {
			case KeyEvent.VK_LEFT:
				if(!eventLeftLock) {
					mario.goIzquierda();
					mario.setState(mario.LEFT);
					eventLeftLock = true;
					if( marioLeft == null )
					{
						marioLeft = new MarioLeftUpdaterThread(mario);
						marioLeft.start();
					}
				}
				break;
			case KeyEvent.VK_RIGHT:
				if(!eventRightLock) {
					mario.goDerecha();
					mario.setState(mario.RIGTH);
					eventRightLock = true;
					if( marioRight == null )
					{
						marioRight = new MarioRightUpdaterThread(mario);
						marioRight.start();
					}
				}
				break;
			case KeyEvent.VK_SPACE:
				if (!eventUpLock)
				{
					mario.goSalto();
					mario.setState(mario.JUMP);
					eventRightLock = false;
					marioUp = new MarioUpUpdaterThread(mario);
					marioUp.start();
					eventUpLock = true;
			
				}
				break;
		}
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		switch (e.getKeyCode()) {
			case KeyEvent.VK_LEFT:
				mario.goQuieto();
				mario.setState(mario.NO_MOVE);
				eventLeftLock = false;
				marioLeft.stop();
				marioLeft = null;
				break;
			case KeyEvent.VK_RIGHT:
				mario.goQuieto();
				mario.setState(mario.NO_MOVE);
				eventRightLock = false;
				marioRight.stop();
				marioRight = null;
				break;
			case KeyEvent.VK_SPACE:
				eventUpLock = false;
				mario.prevStatus();
				break;
		}

	}
		
	

	@Override
	public void keyTyped(KeyEvent e) 
	{

	}
	

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel backgroundPanel;
    private javax.swing.JPanel drawPanel;
    private javax.swing.JLayeredPane layeredPane;
    // End of variables declaration//GEN-END:variables
    private Ini levelINI;
    //Thread locks
    private boolean eventLeftLock = false;
    private boolean eventRightLock = false;
    private boolean eventUpLock = false;
    public static Map levelMap;
    public static Mario mario;
    private MarioLeftUpdaterThread marioLeft;
    private MarioRightUpdaterThread marioRight;
    private MarioUpUpdaterThread marioUp;
    private GravityThread gravityThread;
    private ColisionThread colision;
    private Thread marioRepainter;
}